package main

import (
	"flag"
	"fmt"
	"os"
)

var (
	readOnly    = flag.Bool("r", false, "read only")
	serverPort  = flag.Uint("p", 8080, "server port")
	storageFile = flag.String("f", "lexicon.json", "server storage file")
	dirPublic   = flag.String("d", "public", "resources directory")
)

var (
	lexicon *Lexicon
)

func main() {
	flag.Parse()

	// Attempt to load lexicon from storage file
	f, err := os.Open(*storageFile)
	if os.IsNotExist(err) {
		fmt.Printf("Storage file does not exist:\n\t%s\n", *storageFile)
		fmt.Printf("Creating a new lexicon.\n")
		lexicon, err = new(Lexicon), nil
	} else if err != nil {
		ifErrExit(err, 1)
	} else {
		fmt.Printf("Loading lexicon from file:\n\t%s\n", *storageFile)
		lexicon, err = Load(f)
		f.Close()
		ifErrExit(err, 2)
	}

	// Attempt to launch server
	fmt.Printf("Beginning server on port %d...\n", *serverPort)
	var addr = fmt.Sprintf(":%d", *serverPort)
	err = launchServer(addr, *dirPublic, *readOnly)
	ifErrExit(err, 3)

	fmt.Printf("Lexicrea is now running at:\n\t%s\n", addr)
	fmt.Printf("To exit safely, visit:\n\t%s/exit\n", addr)
}

func exit(save bool) {
	if save {
		saveAndExit()
	} else {
		fmt.Println("Exiting...")
		os.Exit(0)
	}
}

func saveAndExit() {
	fmt.Println("Saving before exit...")

	f, err := os.OpenFile(*storageFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)
	if err != nil {
		goto SaveError
	}
	defer f.Close()

	err = lexicon.Save(f)
	if err != nil {
		goto SaveError
	}

	fmt.Printf("Lexicon saved to file:\n\t%s\n", f.Name())
	safeExit()

SaveError:
	fmt.Printf("Error: %s\n", err)
	fmt.Println("Lexicon could not be saved. Exit cancelled.")
}

func ifErrExit(err error, code int) {
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		fmt.Println("Exiting...")
		os.Exit(code)
	}
}
